﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace _023依赖属性
{
	public class DependencyPropertyStudy:Control
	{

		/// <summary>
		/// 依赖属性定义 propdp快捷键
		/// 如果没有依赖属性，这个框架就是一个控件框架，相当于winform
		/// 控件的依赖属性支持binding
		/// </summary>

		public double ID
		{
			get { return (double)GetValue(IDProperty); }
			set { SetValue(IDProperty, value); }
		}

		// Using a DependencyProperty as the backing store for ID.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty IDProperty =
			DependencyProperty.Register(
				 "ID", 
				typeof(double), 
				typeof(DependencyPropertyStudy), 
				
				new PropertyMetadata(0d,new PropertyChangedCallback(OnValueChanged),OnValueCoerce), OnValueValiDation);


		/// <summary>
		///  2、强制回调，值范围限制
		/// </summary>
		/// <param name="d"></param>
		/// <param name="baseValue"></param>
		/// <returns></returns>
		private static object OnValueCoerce(DependencyObject d, object baseValue)
		{
			if ((double)baseValue > 1000)
			{
				return 200;
			}
			return baseValue;
		}

		/// <summary>
		/// 3、值改变的回调函数
		/// </summary>
		/// <param name="d"></param>
		/// <param name="e"></param>
		private static void OnValueChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
		{
            Console.WriteLine(e.NewValue);
        }

		/// <summary>
		/// 1、值的校验回调函数
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		private static bool OnValueValiDation(object value)
		{
			if ((double)value>1000)
			{
				return false;
			}

			return true;
		}


        public DependencyPropertyStudy()
        {
			this.Loaded += DependencyPropertyStudy_Loaded;
        }

		private void DependencyPropertyStudy_Loaded(object sender, RoutedEventArgs e)
		{
			this.ID = 100;
			this.ID = 102;//值的校验回调false 就报异常 退出

            Console.WriteLine(this.ID);
        }
	}
}
